<?php

use Illuminate\Support\Facades\Event;
class ArticleController extends BaseController {

	protected $layout = 'layouts.master';

	public function view() {
		$this->layout->content = View::make ( 'article.view' );
	}

	public function comment($id) {

		$input = Input::all();
		$type = Evaluate::TYPE_ARTICLE;
		$input['item_id'] = $id;
		Validator::extend ( 'duplicate', function ($attr, $value, $parameters) use ($input, $type) {
			$value = Evaluate::commentExists($type, $input['item_id'], Auth::user()->id);
			return !$value;
		} );

		$rules = array (
				'item_id' => 'duplicate|exists:articles,id',
				'evaluate_comment' => 'required'
		);
		$messages = array(
				'item_id.duplicate' => '你已经评价过',
				'item_id.exists' => '该文章不存在',
				'evaluate_comment.required' => '请输入评价的内容'
		);
		$input = Input::all();
		$input = UtilsHelper::filter_sensitive_word($input);
		$input['item_id'] = $id;
		$validator = Validator::make ( $input, $rules, $messages );
		if ($validator->fails()) {
			return $this->makeView(
					'errors.400',
					$validator->errors(),
					400
			);
		}

		try {
			$article = Article::find($id);
			$evaluate = new Evaluate();
			DB::transaction(function() use($article, $evaluate, $input){
				$article->increment('comments');
				$article->save();
//				$evaluate->score = $input['evaluate_score'];
				$evaluate->comment = $input['evaluate_comment'];
				$evaluate->creator_id = Auth::user()->id;
				$evaluate->item_id = $input['item_id'];
				$evaluate->type = Evaluate::TYPE_ARTICLE;
				$evaluate->save();
			});
			$evaluate->comments_count = $article->comments;
			$user = User::find($evaluate->creator_id);
			$evaluate->avatar = UtilsHelper::getImage($user->avatar, 'img/dfimg.png');
			$evaluate->realname = $user->realname;
		} catch (Exception $ex) {
			Log::error($ex);
			return $this->makeView(
					'errors.503',
					'评论失败，请稍后再试。',
					503
			);
		}
		Event::fire('comment_by_lawyer_for_article', [$id, $input['evaluate_comment'], $article]);

		return $this->makeView(
				'general.200',
				$evaluate->toArray(),
				200
		);

	}

	public function commentList($id){
		try{
			$page = Input::get('page', 1);
			$rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
			$offset = ($page-1) * $rows_per_page;
			$type = Evaluate::TYPE_ARTICLE;
			$comments = Evaluate::getComment($id, $type, $offset, $rows_per_page);
		}catch (Exception $ex) {
			Log::error($ex);
			return $this->makeView(
					'errors.503',
					'获取评论失败，请稍后再试。',
					503
			);
		}
		$commentsArr = $comments->toArray();
		foreach($commentsArr as &$commentArr) {
		    $commentArr['avatar'] = UtilsHelper::getImage($commentArr['avatar'], 'img/dfimg.png');
		}
		return $this->makeView('general.200', $commentsArr);
	}


}